<?php
namespace App\Modules\Manage\Http\Controllers;

use App\Http\Controllers\ManageController;
use App\Modules\Manage\Model\PigProductModel;
use App\Modules\Manage\Model\CategoryModel;
use App\Modules\Manage\Model\PigFileUploadModel;
use Illuminate\Http\Request;


class PigProductController extends ManageController
{
    public function __construct()
    {
        parent::__construct();
        $this->initTheme('manage');
        $this->theme->set('manageType', 'PigProduct');
    }

    public function pigProductList()
    {
        $lists = PigProductModel::pigProductList();
        return $this->theme->scope('manage/pigProductList',['lists'=>$lists])->render();
    }

    public function pigProductInsert(Request $request)
    {
        if($request->isMethod('get')){
            $cates = CategoryModel::cateAll();
            return $this->theme->scope('manage/pigProductInsert',['cates'=>$cates])->render();
        } else {
           $param = $request->except('_token');
           $param['create_time'] = time();
           $param['update_time'] = time();
            $result = pigProductModel::pigProductInsert($param);
            var_export($result);
        }
    }

    public function pigProductUpdate(Request $request)
    {
        if ($request->isMethod('get'))
        {
            $id = $request->id;
            $one = pigProductModel::pigProductGet($id);
            $cates = CategoryModel::cateAll();
//            var_export($one->toArray());die;
            return $this->theme->scope('manage/pigProductUpdate',['one'=>$one,'cates'=>$cates])->render();
        } else {
            $param = $request->except('_token');

            $result = pigProductModel::pigProductUpdate($param);
            if($result) {
                dd('success');
            } else {
                dd('failed');
            }
        }
    }

    public function pigFileUpload()
    {
        $id = Request()->id;
        if (Request()->isMethod('get')){
            $files = PigFileUploadModel::fileGet($id);
            return $this->theme->scope('manage/pigFileUpload',['files'=>$files,'id'=>$id])->render();
        } else {
            $product_id = Request()->input('product_id');
            $file = Request()->file('file');
            $result = \FileClass::uploadFile($file,'sys');
            $result = json_decode($result,true);
            $file_path = $result['data']['url'];
            $data = [];
            $data['product_id'] = $product_id;
            $data['file_path'] = $file_path;
            $res = PigFileUploadModel::fileInsert($data);
//            echo 1;die;
            if ($res) {
                echo 'success';
            } else {
                echo 'failed';
            }
        }
    }

    public function pigFileDel(){
        $id = Request()->input('id');
        $result = PigFileUploadModel::fileDel($id);
        echo $result;
    }
}